Load the necessary libraries
library(rstanarm) # for fitting models in STAN
library(brms) # for fitting models in STAN
library(standist) # for exploring distributions
library(coda) # for diagnostics
library(bayesplot) # for diagnostics
library(ggmcmc) # for MCMC diagnostics
library(DHARMa) # for residual diagnostics
library(rstan) # for interfacing with STAN
library(emmeans) # for marginal means etc
library(broom) # for tidying outputs
library(tidybayes) # for more tidying outputs
library(HDInterval) # for HPD intervals
library(ggeffects) # for partial plots
library(tidyverse) # for data wrangling etc
library(broom.mixed) # for summarising models
library(posterior) # for posterior draws
library(ggeffects) # for partial effects plots
library(patchwork) # for multi-panel figures
theme_set(theme_grey()) # put the default ggplot theme back
Here is an example from Fowler, Cohen, and Jarvis (1998). An agriculturalist was interested in the effects of fertilizer load on the yield of grass. Grass seed was sown uniformly over an area and different quantities of commercial fertilizer were applied to each of ten 1 m2 randomly located plots. Two months later the grass from each plot was harvested, dried and weighed. The data are in the file fertilizer.csv in the data folder.
| FERTILIZER | YIELD |
|---|---|
| 25 | 84 |
| 50 | 80 |
| 75 | 90 |
| 100 | 154 |
| 125 | 148 |
| ... | ... |
| FERTILIZER: | Mass of fertilizer (g.m-2) - Predictor variable |
| YIELD: | Yield of grass (g.m-2) - Response variable |
The aim of the analysis is to investigate the relationship between fertilizer concentration and grass yield.
We will start off by reading in the Fertilizer data. There are many functions in R that can read in a CSV file. We will use a the read_csv() function as it is part of the tidyverse ecosystem.
fert <- read_csv("../public/data/fertilizer.csv", trim_ws = TRUE)
glimpse(fert)
## Rows: 10
## Columns: 2
## $ FERTILIZER <dbl> 25, 50, 75, 100, 125, 150, 175, 200, 225, 250
## $ YIELD <dbl> 84, 80, 90, 154, 148, 169, 206, 244, 212, 248
The individual responses (\(y_i\), observed yields) are each expected to have been independently drawn from normal (Gaussian) distributions (\(\mathcal{N}\)). These distributions represent all the possible yields we could have obtained at the specific (\(i^th\)) level of Fertilizer. Hence the \(i^th\) yield observation is expected to have been drawn from a normal distribution with a mean of \(\mu_i\).
Although each distribution is expected to come from populations that differ in their means, we assume that all of these distributions have the same variance (\(\sigma^2\)).
We need to supply priors for each of the parameters to be estimated (\(\beta_0\), \(\beta_1\) and \(\sigma\)). Whilst we want these priors to be sufficiently vague as to not influence the outcomes of the analysis (and thus be equivalent to the frequentist analysis), we do not want the priors to be so vague (wide) that they permit the MCMC sampler to drift off into parameter space that is both illogical as well as numerically awkward.
As a starting point, lets assign the following priors:
Note, when fitting models through either rstanarm or brms, the priors assume that the predictor(s) have been centred and are to be applied on the link scale. In this case the link scale is an identity.
Model formula: \[ \begin{align} y_i &\sim{} \mathcal{N}(\mu_i, \sigma^2)\\ \mu_i &= \beta_0 + \beta_1 x_i\\ \beta_0 &\sim{} \mathcal{N}(0,100)\\ \beta_1 &\sim{} \mathcal{N}(0,10)\\ \sigma &\sim{} \mathcal{cauchy}(0,5)\\ OR\\ \sigma &\sim{} \mathcal{Exp}(1)\\ OR\\ \sigma &\sim{} \mathcal{gamma}(2,1)\\ \end{align} \]
Note, for routines that take more than a couple of seconds to perform (such as most Bayesian models), it is a good idea to cache the Rmarkdown chunks in which the routine is performed. That way, the routine will only be run the first time and any objects generated will be stored for future use. Thereafter, provided the code has not changed, the routine will not be re-run. Rather, knitr will just retrieve the cached objects and continue on.
For the purpose of comparing the frequentist and Bayesian outcomes, it might be useful to start by fitting the frequentist simple linear model. We will also fit this model with the predictor (fertilizer concentration) centred.
summary(lm(YIELD ~ FERTILIZER, data = fert))
##
## Call:
## lm(formula = YIELD ~ FERTILIZER, data = fert)
##
## Residuals:
## Min 1Q Median 3Q Max
## -22.79 -11.07 -5.00 12.00 29.79
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 51.93333 12.97904 4.001 0.00394 **
## FERTILIZER 0.81139 0.08367 9.697 1.07e-05 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 19 on 8 degrees of freedom
## Multiple R-squared: 0.9216, Adjusted R-squared: 0.9118
## F-statistic: 94.04 on 1 and 8 DF, p-value: 1.067e-05
summary(lm(YIELD ~ scale(FERTILIZER, scale = FALSE), data = fert))
##
## Call:
## lm(formula = YIELD ~ scale(FERTILIZER, scale = FALSE), data = fert)
##
## Residuals:
## Min 1Q Median 3Q Max
## -22.79 -11.07 -5.00 12.00 29.79
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 163.50000 6.00813 27.213 3.58e-09 ***
## scale(FERTILIZER, scale = FALSE) 0.81139 0.08367 9.697 1.07e-05 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 19 on 8 degrees of freedom
## Multiple R-squared: 0.9216, Adjusted R-squared: 0.9118
## F-statistic: 94.04 on 1 and 8 DF, p-value: 1.067e-05
In rstanarm, the default priors are designed to be weakly informative. They are chosen to provide moderate regularisation (to help prevent over-fitting) and help stabilise the computations.
fert.rstanarm <- stan_glm(YIELD ~ FERTILIZER,
data = fert,
iter = 5000,
warmup = 1000,
chains = 3,
thin = 5,
refresh = 0
)
In the above:
Having allowed rstanarm to formulate its own weakly informative priors, it is a good idea to explore what they are. Firstly, out of curiosity, it might be interesting to see what it has chosen. However, more importantly, we need to be able to document what the priors were and the rstanarm development team make it very clear that there is no guarantee that the default priors will remain the same into the future.
prior_summary(fert.rstanarm)
## Priors for model 'fert.rstanarm'
## ------
## Intercept (after predictors centered)
## Specified prior:
## ~ normal(location = 164, scale = 2.5)
## Adjusted prior:
## ~ normal(location = 164, scale = 160)
##
## Coefficients
## Specified prior:
## ~ normal(location = 0, scale = 2.5)
## Adjusted prior:
## ~ normal(location = 0, scale = 2.1)
##
## Auxiliary (sigma)
## Specified prior:
## ~ exponential(rate = 1)
## Adjusted prior:
## ~ exponential(rate = 0.016)
## ------
## See help('prior_summary.stanreg') for more details
This tells us:
mean(fert$YIELD)
## [1] 163.5
sd(fert$YIELD)
## [1] 63.97439
2.5 * sd(fert$YIELD)
## [1] 159.936
2.5 * sd(fert$YIELD) / sd(fert$FERTILIZER)
## [1] 2.113004
rstanarm, this is a exponential with a rate of 1 which is then adjusted by division with the standard deviation of the response.1 / sd(fert$FERTILIZER)
## [1] 0.01321157
One way to assess the priors is to have the MCMC sampler sample purely from the prior predictive distribution without conditioning on the observed data. Doing so provides a glimpse at the range of predictions possible under the priors. On the one hand, wide ranging predictions would ensure that the priors are unlikely to influence the actual predictions once they are conditioned on the data. On the other hand, if they are too wide, the sampler is being permitted to traverse into regions of parameter space that are not logically possible in the context of the actual underlying ecological context. Not only could this mean that illogical parameter estimates are possible, when the sampler is traversing regions of parameter space that are not supported by the actual data, the sampler can become unstable and have difficulty.
We can draw from the prior predictive distribution instead of conditioning on the response, by updating the model and indicating prior_PD=TRUE. After refitting the model in this way, we can plot the predictions to gain insights into the range of predictions supported by the priors alone.
fert.rstanarm1 <- update(fert.rstanarm, prior_PD = TRUE)
ggpredict(fert.rstanarm1) %>% plot(add.data = TRUE)
## $FERTILIZER
Conclusions:
The following link provides some guidance about defining priors. [https://github.com/stan-dev/stan/wiki/Prior-Choice-Recommendations]
When defining our own priors, we typically do not want them to be scaled.
If we wanted to define our own priors that were less vague, yet still not likely to bias the outcomes, we could try the following priors (mainly plucked out of thin air):
I will also overlay the raw data for comparison.
fert.rstanarm2 <- stan_glm(YIELD ~ FERTILIZER,
data = fert,
prior_intercept = normal(164, 10, autoscale = FALSE),
prior = normal(0, 1, autoscale = FALSE),
prior_aux = cauchy(0, 2, autoscale = FALSE),
prior_PD = TRUE,
iter = 5000, warmup = 1000,
chains = 3, thin = 5, refresh = 0
)
ggpredict(fert.rstanarm2) %>%
plot(add.data = TRUE)
## $FERTILIZER
Now lets refit, conditioning on the data.
fert.rstanarm3 <- update(fert.rstanarm2, prior_PD = FALSE)
posterior_vs_prior(fert.rstanarm3,
color_by = "vs", group_by = TRUE,
facet_args = list(scales = "free_y")
)
Conclusions:
ggpredict(fert.rstanarm3) %>% plot(add.data = TRUE)
## $FERTILIZER
In brms, the default priors are designed to be weakly informative. They are chosen to provide moderate regularisation (to help prevent over-fitting) and help stabilise the computations.
Unlike rstanarm, brms models must be compiled before they start sampling. For most models, the compilation of the stan code takes around 45 seconds.
fert.brm <- brm(bf(YIELD ~ FERTILIZER),
data = fert,
iter = 5000,
warmup = 1000,
chains = 3,
thin = 5,
refresh = 0
)
In the above:
brms can define models that are not possible by most other routines. To facilitate this enhanced functionality, we usually define a brms formula within its own bf() function along with the family (in this case, it is Gaussian, which is the default and therefore can be omitted.)The returned object (a list) contains a range of objects. The output from rstan is contained in the fit list item.
fert.brm %>% names()
## [1] "formula" "data" "prior" "data2" "stanvars" "model"
## [7] "ranef" "save_pars" "algorithm" "backend" "threads" "opencl"
## [13] "fit" "criteria" "file" "version" "family" "autocor"
## [19] "cov_ranef" "stan_funs" "data.name"
Having allowed brms to formulate its own weakly informative priors, it is a good idea to explore what they are. Firstly, out of curiosity, it might be interesting to see what it has chosen. However, more importantly, we need to be able to document what the priors were and the brms development team make it very clear that there is no guarantee that the default priors will remain the same into the future.
prior_summary(fert.brm)
## prior class coef group resp dpar nlpar bound source
## (flat) b default
## (flat) b FERTILIZER (vectorized)
## student_t(3, 161.5, 90.4) Intercept default
## student_t(3, 0, 90.4) sigma default
This tells us:
median(fert$YIELD)
## [1] 161.5
mad(fert$YIELD)
## [1] 90.4386
mad is the median absolute deviation. mad is to var as median is to mean.
standist::visualize("student_t(3,161.5,90.4)", xlim = c(-100, 1000))
for the beta coefficients (in this case, just the slope), the default prior is a improper flat prior. A flat prior essentially means that any value between negative infinity and positive infinity are equally likely. Whilst this might seem reckless, in practice, it seems to work reasonably well for non-intercept beta parameters.
the prior on sigma is also a student t (although only the positive half is used in the stan code), with mean of 0 and standard deviation of 90.4.
standist::visualize("student_t(3,0,90.4)", xlim = c(-10, 500))
One way to assess the priors is to have the MCMC sampler sample purely from the prior predictive distribution without conditioning on the observed data. Doing so provides a glimpse at the range of predictions possible under the priors. On the one hand, wide ranging predictions would ensure that the priors are unlikely to influence the actual predictions once they are conditioned on the data. On the other hand, if they are too wide, the sampler is being permitted to traverse into regions of parameter space that are not logically possible in the context of the actual underlying ecological context. Not only could this mean that illogical parameter estimates are possible, when the sampler is traversing regions of parameter space that are not supported by the actual data, the sampler can become unstable and have difficulty.
In brms, we can inform the sampler to draw from the prior predictive distribution instead of conditioning on the response, by running the model with the sample_prior = 'only' argument. Unfortunately, this cannot be applied when there are flat priors (since the posteriors will necessarily extend to negative and positive infinity). Therefore, in order to use this useful routine, we need to make sure that we have defined a proper prior for all parameters.
Lets try a Gaussian (normal) distribution for the slope. We will start with what is likely to be a very wide distribution (wide with respect to what we know about the likely slope).
standist::visualize("normal(0, 10)", xlim = c(-50, 50))
standist::visualize("normal(0, 0.1)", xlim = c(-1, 1))
fert.brm1 <- brm(bf(YIELD ~ FERTILIZER),
data = fert,
prior = prior(normal(0, 10), class = "b"),
sample_prior = "only",
iter = 5000,
warmup = 1000,
chains = 3,
thin = 5,
refresh = 0
)
fert.brm1 %>%
ggpredict() %>%
plot(add.data = TRUE)
## $FERTILIZER
fert.brm1 %>%
ggemmeans(~FERTILIZER) %>%
plot(add.data = TRUE)
fert.brm1 %>%
conditional_effects() %>%
plot(points = TRUE)
Conclusions:
The following link provides some guidance about defining priors. [https://github.com/stan-dev/stan/wiki/Prior-Choice-Recommendations]
When defining our own priors, we typically do not want them to be scaled.
If we wanted to define our own priors that were less vague, yet still not likely to bias the outcomes, we could try the following priors (which I have mainly plucked out of thin air):
standist::visualize("normal(164, 10)", xlim = c(-100, 300))
standist::visualize("normal(0, 1)", xlim = c(-10, 10))
standist::visualize("cauchy(0, 2)", xlim = c(-10, 10))
standist::visualize("gamma(2, 1)", xlim = c(0, 10))
standist::visualize(
"student_t(3, 0, 90.4)",
"cauchy(0, 2)",
"gamma(2, 1)",
"gamma(2, 0.5)",
"gamma(2, 0.2)",
xlim = c(0, 20)
)
I will also overlay the raw data for comparison.
priors <- prior(normal(164, 10), class = "Intercept") +
prior(normal(0, 1), class = "b") +
prior(gamma(2, 1), class = "sigma")
fert.brm2 <- brm(bf(YIELD ~ FERTILIZER),
data = fert,
prior = priors,
sample_prior = "only",
iter = 5000,
warmup = 1000,
chains = 3,
thin = 5,
refresh = 0
)
fert.brm2 %>%
ggemmeans(~FERTILIZER) %>%
plot(add.data = TRUE)
# OR
fert.brm2 %>%
conditional_effects() %>%
plot(points = TRUE)
fert.brm3 <- update(fert.brm2, sample_prior = "yes", refresh = 0)
fert.brm3 <- brm(bf(YIELD ~ FERTILIZER),
data = fert,
prior = priors,
sample_prior = "yes",
iter = 5000,
warmup = 1000,
chains = 3,
thin = 5,
refresh = 0
)
When we have indicated that the posterior should be informed by both the prior and the posterior, both prior (governed by priors alone) and posterior (governed by both priors and data/likelihood) draws are returned. These can be compared by exploring the probabilities associated with specific hypotheses - the most obvious of which is that of no effect (that the parameter = 0).
When doing so, ideally the posterior should be distinct from the prior. If this is not the case, it might suggest that the posteriors are being too strongly driven by the priors.
fert.brm3 %>% get_variables()
## [1] "b_Intercept" "b_FERTILIZER" "sigma" "prior_Intercept"
## [5] "prior_b" "prior_sigma" "lp__" "accept_stat__"
## [9] "stepsize__" "treedepth__" "n_leapfrog__" "divergent__"
## [13] "energy__"
## fert.brm3 %>% hypothesis('Intercept=0', class='b') %>% plot
fert.brm3 %>%
hypothesis("FERTILIZER = 0") %>%
plot()
## fert.brm3 %>% hypothesis('scaleFERTILIZERscaleEQFALSE=0') %>% plot
fert.brm3 %>%
hypothesis("sigma = 0", class = "") %>%
plot()
Unfortunately, it is not possible to do this comparison sensibly for the intercept. The reason for this is that the prior for intercept was applied to an intercept that is associated with centred continuous predictors (predictors are centred behind the scenes). Since we did not centre the predictor, the intercept returned is as if uncentred. Hence, the prior and posterior are on different scales.
fert.brm3 %>% get_variables()
## [1] "b_Intercept" "b_FERTILIZER" "sigma" "prior_Intercept"
## [5] "prior_b" "prior_sigma" "lp__" "accept_stat__"
## [9] "stepsize__" "treedepth__" "n_leapfrog__" "divergent__"
## [13] "energy__"
fert.brm3 %>%
posterior_samples() %>%
select(-`lp__`) %>%
pivot_longer(cols = everything(), names_to = "key", values_to = "value") %>%
mutate(
Type = ifelse(str_detect(key, "prior"), "Prior", "b"),
Class = ifelse(str_detect(key, "Intercept"), "Intercept",
ifelse(str_detect(key, "sigma"), "Sigma", "b")
)
) %>%
ggplot(aes(x = Type, y = value)) +
stat_pointinterval() +
facet_wrap(~Class, scales = "free")
fert.brm3 %>% standata()
## $N
## [1] 10
##
## $Y
## [1] 84 80 90 154 148 169 206 244 212 248
##
## $K
## [1] 2
##
## $X
## Intercept FERTILIZER
## 1 1 25
## 2 1 50
## 3 1 75
## 4 1 100
## 5 1 125
## 6 1 150
## 7 1 175
## 8 1 200
## 9 1 225
## 10 1 250
## attr(,"assign")
## [1] 0 1
##
## $prior_only
## [1] 0
##
## attr(,"class")
## [1] "standata" "list"
fert.brm3 %>% stancode()
## // generated with brms 2.16.3
## functions {
## }
## data {
## int<lower=1> N; // total number of observations
## vector[N] Y; // response variable
## int<lower=1> K; // number of population-level effects
## matrix[N, K] X; // population-level design matrix
## int prior_only; // should the likelihood be ignored?
## }
## transformed data {
## int Kc = K - 1;
## matrix[N, Kc] Xc; // centered version of X without an intercept
## vector[Kc] means_X; // column means of X before centering
## for (i in 2:K) {
## means_X[i - 1] = mean(X[, i]);
## Xc[, i - 1] = X[, i] - means_X[i - 1];
## }
## }
## parameters {
## vector[Kc] b; // population-level effects
## real Intercept; // temporary intercept for centered predictors
## real<lower=0> sigma; // dispersion parameter
## }
## transformed parameters {
## }
## model {
## // likelihood including constants
## if (!prior_only) {
## target += normal_id_glm_lpdf(Y | Xc, Intercept, b, sigma);
## }
## // priors including constants
## target += normal_lpdf(b | 0, 1);
## target += normal_lpdf(Intercept | 164, 10);
## target += gamma_lpdf(sigma | 2, 1);
## }
## generated quantities {
## // actual population-level intercept
## real b_Intercept = Intercept - dot_product(means_X, b);
## // additionally sample draws from priors
## real prior_b = normal_rng(0,1);
## real prior_Intercept = normal_rng(164,10);
## real prior_sigma = gamma_rng(2,1);
## // use rejection sampling for truncated priors
## while (prior_sigma < 0) {
## prior_sigma = gamma_rng(2,1);
## }
## }
library(INLA)
In INLA, the default priors are designed to be diffuse or weak. They are chosen to provide moderate regularisation (to help prevent over-fitting) and help stabilise the computations.
fert.inla <- inla(YIELD ~ FERTILIZER,
data = fert,
family = "gaussian",
control.compute = list(config = TRUE, dic = TRUE, waic = TRUE, cpo = TRUE)
)
In the above:
the formula, data and family arguments should be familiar as they are the same as for other models in R.
control.compute: allows us to indicate what additional actions should be performed during the model fitting. In this case, we have indicated:
dic: Deviance information criterionwaic: Wantanabe information creterioncpo: out-of-sample estimates (measures of fit)config: return the full configuration - to allow drawing from the posterior.fert.inla %>% names()
## [1] "names.fixed" "summary.fixed"
## [3] "marginals.fixed" "summary.lincomb"
## [5] "marginals.lincomb" "size.lincomb"
## [7] "summary.lincomb.derived" "marginals.lincomb.derived"
## [9] "size.lincomb.derived" "mlik"
## [11] "cpo" "po"
## [13] "waic" "model.random"
## [15] "summary.random" "marginals.random"
## [17] "size.random" "summary.linear.predictor"
## [19] "marginals.linear.predictor" "summary.fitted.values"
## [21] "marginals.fitted.values" "size.linear.predictor"
## [23] "summary.hyperpar" "marginals.hyperpar"
## [25] "internal.summary.hyperpar" "internal.marginals.hyperpar"
## [27] "offset.linear.predictor" "model.spde2.blc"
## [29] "summary.spde2.blc" "marginals.spde2.blc"
## [31] "size.spde2.blc" "model.spde3.blc"
## [33] "summary.spde3.blc" "marginals.spde3.blc"
## [35] "size.spde3.blc" "logfile"
## [37] "misc" "dic"
## [39] "mode" "neffp"
## [41] "joint.hyper" "nhyper"
## [43] "version" "Q"
## [45] "graph" "ok"
## [47] "cpu.used" "all.hyper"
## [49] ".args" "call"
## [51] "model.matrix"
Having allowed INLA to formulate its own “minimally informative” priors, it is a good idea to explore what they are. Firstly, out of curiosity, it might be interesting to see what it has chosen. However, more importantly, we need to be able to document what the priors were and the INLA development team make it very clear that there is no guarantee that the default priors will remain the same into the future.
In calcutating the posterior mode of hyperparameters, it is efficient to maximising the sum of the (log)-likelihood and the (log)-prior, hence, priors are defined on a log-scale. The canonical prior for variance is the gamma prior, hence in INLA, this is a loggamma.
They are also defined according to their mean and precision (inverse-scale, rather than variance). Precision is \(1/\sigma\).
To explore the default priors used by INLA, we can issue the following on the fitted model:
inla.priors.used(fert.inla)
## section=[family]
## tag=[INLA.Data1] component=[gaussian]
## theta1:
## parameter=[log precision]
## prior=[loggamma]
## param=[1e+00, 5e-05]
## section=[fixed]
## tag=[(Intercept)] component=[(Intercept)]
## beta:
## parameter=[(Intercept)]
## prior=[normal]
## param=[0, 0]
## tag=[FERTILIZER] component=[FERTILIZER]
## beta:
## parameter=[FERTILIZER]
## prior=[normal]
## param=[0.000, 0.001]
The above indicates:
standist::visualize("gamma(1, 0.00005)", xlim=c(-100,100000))
standist::visualize("normal(0, 31)", xlim=c(-100,100))
Family variance
In order to drive the specification of weekly informative priors for variance components (a prior that allows the data to dictate the parameter estimates whilst constraining the range of the marginal distribution within sensible bounds), we can consider the range over which the marginal distribution of variance components would be sensible. For the range [-R,R], the equivalent gamma parameters:
\[ \begin{align} a &= \frac{d}{2}\\ b &= \frac{R^2d}{2*(t^d_{1-(1-q)/2})^2} \end{align} \]
where \(d\) is the degrees of freedom (for Cauchy marginal, \(d=1\)) and \(t^d_{1-(1-q)/2}\) is the \(q_{th}\) quantile of a Student t with \(d\) degrees of freedom. Hence if we considered variance likely to be in the range of [0,10], we could define a loggamma prior of:
\[ \begin{align} a &= \frac{1}{2} = 0.5\\ b &= \frac{10^2}{2*161.447} = 0.31\\ \tau &\sim{} log\Gamma(0.5,0.31) \end{align} \]
standist::visualize("gamma(0.5, 0.31)", xlim=c(-5,20))
Intercept
The default prior on the intercept is a Gaussian with mean of 0 and precision of 0 (and thus effectively a flat uniform). Alternatively, we could define priors on the intercept that are more realistic. For example, we know that the median grass yield is 80. Hence, the intercept is likely to be relatively close to this value. Note, arguably it would be more sensible to center the predictor variable (fertiliser concentration) so that the intercept would represent the yeild at the average fertiliser concentration. Furthermore, this would also be more computationally expedient. In fact, the only reason we are not doing so is so that we can directly compare the parameter estimates to the frequentist linear model.
min(fert$YIELD)
## [1] 80
median(fert$YIELD)
## [1] 161.5
mad(fert$YIELD)
## [1] 90.4386
We will multiply the variability (90.4386) by 3 so as to estimate an envelope that so as to fully capture the full range of expected values (271.3158.
standist::visualize("normal(80, 271.32)", xlim=c(-700,1000))
We could use these values as the basis for weekly informative priors on the intercept. Note, as INLA priors are expressed in terms of precision rather than variance, an equvilent prior would be \(\sim{}~\mathcal{N}(80, 0.00001)\) (e.g. \(1/(MAD\times 3)^2\)).
Fixed effects
The priors for the fixed effects (slope) is a Gaussian (normal) distributions with mean of 0 and precision (0.001). This implies that the prior for slope has a standard deviation of approximately 31 (since \(\sigma = \frac{1}{\sqrt{\tau}}\)). As a general rule, three standard deviations envelopes most of a distribution, and thus this prior defines a distribution whose density is almost entirely within the range [-93,93]. Arguably, this is very wide for the slope given the range of the predictor variable.
In order to generate realistic informative Gaussian priors (for the purpose of constraining the posterior to a logical range) for fixed parameters, the following formulae are useful:
\[ \begin{align} \mu &= \frac{z_2\theta_1 - z_1\theta_2}{z_2-z_1}\\ \sigma &= \frac{\theta_2 - \theta_1}{z_2-z_1} \end{align} \]
where \(\theta_1\) and \(\theta_2\) are the quantiles on the response scale and \(z_1\) and \(z_2\) are the corresponding quantiles on the standard normal scale. Hence, if we considered that the slope is likely to be in the range of [-10,10], we could specify a Normal prior with mean of \(\mu=\frac{(qnorm(0.5,0,1)*0) - (qnorm(0.975,0,1)*10)}{10-0} = 0\) and a standard deviation of \(\sigma^2=\frac{10 - 0}{qnorm(0.975,0,1)-qnorm(0.5,0,1)} = 5.102\). In INLA (which defines priors in terms of precision rather than standard deviation), the associated prior would be \(\beta \sim{} \mathcal{N}(0, 0.0384)\).
standist::visualize("normal(0, 5.102)", xlim=c(-20,20))
In order to define each of the above priors, we could modify the inla call:
fert.inla1 <- inla(YIELD ~ FERTILIZER,
data = fert,
family = "gaussian",
control.fixed = list(
mean.intercept = 80,
prec.intercept = 0.00001,
mean = 0,
prec = 0.0384
),
control.family = list(hyper = list(prec = list(
prior = "loggamma",
param = c(0.5, 0.31)
))),
control.compute = list(config = TRUE, dic = TRUE, waic = TRUE, cpo = TRUE)
)
Lets briefly compare the parameter estimates. In the following, Model.1 is the model that employed the default priors and Model.2 is the model that employed the user defined priors.
## Fixed effects
rbind(Model.1 = fert.inla$summary.fixed, Model.2 = fert.inla1$summary.fixed)
## Family hyperpriors (variance)
rbind(Model.1 = fert.inla$summary.hyperpar, Model.2 = fert.inla1$summary.hyperpar)
It is clear that the two models yeild very similar parameter estimates.
Note, the following will not appear in this tutorial as the INLA plotting function has been really awkwardly written and is not compatible with Rmd.
plot(fert.inla1,
plot.fixed.effects = TRUE,
plot.lincomb = FALSE,
plot.random.effects = FALSE,
plot.hyperparameters = TRUE,
plot.predictor = FALSE,
plot.q = FALSE,
plot.cpo = FALSE,
plot.prior = TRUE,
single = FALSE
)
library(INLAutils)
plot_fixed_marginals(fert.inla1, priors = TRUE)
library(INLAutils)
plot_hyper_marginals(fert.inla1, CI = TRUE)
Or the effects as a single figure..
library(INLAutils)
autoplot(fert.inla1)
marg.fix <- fert.inla1$marginals.fixed
(nm <- names(marg.fix))
## [1] "(Intercept)" "FERTILIZER"
p <- vector("list", length(nm))
for (wch in 1:length(nm)) {
xy <- INLA:::inla.get.prior.xy(
section = "fixed", hyperid = nm[1],
all.hyper = fert.inla1$all.hyper,
range = 3 * range(marg.fix[[wch]][, "x"])
)
p[[wch]] <- ggplot() +
geom_density(
data = as.data.frame(marg.fix[[wch]]),
aes(x = x, y = y, fill = "Posterior"), alpha = 0.2,
stat = "Identity"
) +
geom_density(
data = as.data.frame(xy), aes(x = x, y = y, fill = "Prior"), alpha = 0.2,
stat = "Identity"
)
}
patchwork::wrap_plots(p)
MCMC sampling behaviour
Since the purpose of the MCMC sampling is to estimate the posterior of an unknown joint likelihood, it is important that we explore a range of diagnostics designed to help identify when the resulting likelihood might not be accurate.
available_mcmc()
| Package | Description | function | rstanarm | brms |
|---|---|---|---|---|
| bayesplot | Traceplot | mcmc_trace |
plot(mod, plotfun='trace') |
mcmc_plot(mod, type='trace') |
| Density plot | mcmc_dens |
plot(mod, plotfun='dens') |
mcmc_plot(mod, type='dens') |
|
| Density & Trace | mcmc_combo |
plot(mod, plotfun='combo') |
mcmc_plot(mod, type='combo') |
|
| ACF | mcmc_acf_bar |
plot(mod, plotfun='acf_bar') |
mcmc_plot(mod, type='acf_bar') |
|
| Rhat hist | mcmc_rhat_hist |
plot(mod, plotfun='rhat_hist') |
mcmc_plot(mod, type='rhat_hist') |
|
| No. Effective | mcmc_neff_hist |
plot(mod, plotfun='neff_hist') |
mcmc_plot(mod, type='neff_hist') |
|
| rstan | Traceplot | stan_trace |
stan_trace(mod) |
stan_trace(mod) |
| ACF | stan_ac |
stan_ac(mod) |
stan_ac(mod) |
|
| Rhat | stan_rhat |
stan_rhat(mod) |
stan_rhat(mod) |
|
| No. Effective | stan_ess |
stan_ess(mod) |
stan_ess(mod) |
|
| Density plot | stan_dens |
stan_dens(mod) |
stan_dens(mod) |
|
| ggmcmc | Traceplot | ggs_traceplot |
ggs_traceplot(ggs(mod)) |
ggs_traceplot(ggs(mod)) |
| ACF | ggs_autocorrelation |
ggs_autocorrelation(ggs(mod)) |
ggs_autocorrelation(ggs(mod)) |
|
| Rhat | ggs_Rhat |
ggs_Rhat(ggs(mod)) |
ggs_Rhat(ggs(mod)) |
|
| No. Effective | ggs_effective |
ggs_effective(ggs(mod)) |
ggs_effective(ggs(mod)) |
|
| Cross correlation | ggs_crosscorrelation |
ggs_crosscorrelation(ggs(mod)) |
ggs_crosscorrelation(ggs(mod)) |
|
| Scale reduction | ggs_grb |
ggs_grb(ggs(mod)) |
ggs_grb(ggs(mod)) |
|
In addition to the regular model diagnostics checking, for Bayesian analyses, it is also necessary to explore the MCMC sampling diagnostics to be sure that the chains are well mixed and have converged on a stable posterior.
There are a wide variety of tests that range from the big picture, overall chain characteristics to the very specific detailed tests that allow the experienced modeller to drill down to the very fine details of the chain behaviour. Furthermore, there are a multitude of packages and approaches for exploring these diagnostics.
The bayesplot package offers a range of MCMC diagnostics as well as Posterior Probability Checks (PPC), all of which have a convenient plot() interface. Lets start with the MCMC diagnostics.
available_mcmc()
## bayesplot MCMC module:
## mcmc_acf
## mcmc_acf_bar
## mcmc_areas
## mcmc_areas_data
## mcmc_areas_ridges
## mcmc_areas_ridges_data
## mcmc_combo
## mcmc_dens
## mcmc_dens_chains
## mcmc_dens_chains_data
## mcmc_dens_overlay
## mcmc_hex
## mcmc_hist
## mcmc_hist_by_chain
## mcmc_intervals
## mcmc_intervals_data
## mcmc_neff
## mcmc_neff_data
## mcmc_neff_hist
## mcmc_nuts_acceptance
## mcmc_nuts_divergence
## mcmc_nuts_energy
## mcmc_nuts_stepsize
## mcmc_nuts_treedepth
## mcmc_pairs
## mcmc_parcoord
## mcmc_parcoord_data
## mcmc_rank_hist
## mcmc_rank_overlay
## mcmc_recover_hist
## mcmc_recover_intervals
## mcmc_recover_scatter
## mcmc_rhat
## mcmc_rhat_data
## mcmc_rhat_hist
## mcmc_scatter
## mcmc_trace
## mcmc_trace_data
## mcmc_trace_highlight
## mcmc_violin
Of these, we will focus on:
plot(fert.rstanarm3, plotfun = "mcmc_trace")
The chains appear well mixed and very similar
plot(fert.rstanarm3, "acf_bar")
There is no evidence of autocorrelation in the MCMC samples
plot(fert.rstanarm3, "rhat_hist")
All Rhat values are below 1.05, suggesting the chains have converged.
neff (number of effective samples): the ratio of the number of effective samples (those not rejected by the sampler) to the number of samples provides an indication of the effectiveness (and efficiency) of the MCMC sampler. Ratios that are less than 0.5 for a parameter suggest that the sampler spent considerable time in difficult areas of the sampling domain and rejected more than half of the samples (replacing them with the previous effective sample).
If the ratios are low, tightening the priors may help.
plot(fert.rstanarm3, "neff_hist")
Ratios all very high.
plot(fert.rstanarm3, "combo")
plot(fert.rstanarm3, "violin")
The rstan package offers a range of MCMC diagnostics. Lets start with the MCMC diagnostics.
Of these, we will focus on:
stan_trace(fert.rstanarm3)
The chains appear well mixed and very similar
stan_ac(fert.rstanarm3)
There is no evidence of autocorrelation in the MCMC samples
stan_rhat(fert.rstanarm3)
All Rhat values are below 1.05, suggesting the chains have converged.
stan_ess (number of effective samples): the ratio of the number of effective samples (those not rejected by the sampler) to the number of samples provides an indication of the effectiveness (and efficiency) of the MCMC sampler. Ratios that are less than 0.5 for a parameter suggest that the sampler spent considerable time in difficult areas of the sampling domain and rejected more than half of the samples (replacing them with the previous effective sample).
If the ratios are low, tightening the priors may help.
stan_ess(fert.rstanarm3)
Ratios all very high.
stan_dens(fert.rstanarm3, separate_chains = TRUE)
The ggmean package also has a set of MCMC diagnostic functions. Lets start with the MCMC diagnostics.
Of these, we will focus on:
fert.ggs <- ggs(fert.rstanarm3)
ggs_traceplot(fert.ggs)
The chains appear well mixed and very similar
ggs_autocorrelation(fert.ggs)
There is no evidence of autocorrelation in the MCMC samples
ggs_Rhat(fert.ggs)
All Rhat values are below 1.05, suggesting the chains have converged.
stan_ess (number of effective samples): the ratio of the number of effective samples (those not rejected by the sampler) to the number of samples provides an indication of the effectiveness (and efficiency) of the MCMC sampler. Ratios that are less than 0.5 for a parameter suggest that the sampler spent considerable time in difficult areas of the sampling domain and rejected more than half of the samples (replacing them with the previous effective sample).
If the ratios are low, tightening the priors may help.
ggs_effective(fert.ggs)
Ratios all very high.
ggs_crosscorrelation(fert.ggs)
ggs_grb(fert.ggs)
The bayesplot package offers a range of MCMC diagnostics as well as Posterior Probability Checks (PPC), all of which have a convenient plot() interface. Lets start with the MCMC diagnostics.
available_mcmc()
## bayesplot MCMC module:
## mcmc_acf
## mcmc_acf_bar
## mcmc_areas
## mcmc_areas_data
## mcmc_areas_ridges
## mcmc_areas_ridges_data
## mcmc_combo
## mcmc_dens
## mcmc_dens_chains
## mcmc_dens_chains_data
## mcmc_dens_overlay
## mcmc_hex
## mcmc_hist
## mcmc_hist_by_chain
## mcmc_intervals
## mcmc_intervals_data
## mcmc_neff
## mcmc_neff_data
## mcmc_neff_hist
## mcmc_nuts_acceptance
## mcmc_nuts_divergence
## mcmc_nuts_energy
## mcmc_nuts_stepsize
## mcmc_nuts_treedepth
## mcmc_pairs
## mcmc_parcoord
## mcmc_parcoord_data
## mcmc_rank_hist
## mcmc_rank_overlay
## mcmc_recover_hist
## mcmc_recover_intervals
## mcmc_recover_scatter
## mcmc_rhat
## mcmc_rhat_data
## mcmc_rhat_hist
## mcmc_scatter
## mcmc_trace
## mcmc_trace_data
## mcmc_trace_highlight
## mcmc_violin
Of these, we will focus on:
fert.brm3 %>% mcmc_plot(type = "combo")
fert.brm3 %>% mcmc_plot(type = "trace")
fert.brm3 %>% mcmc_plot(type = "dens_overlay")
The chains appear well mixed and very similar
fert.brm3 %>% mcmc_plot(type = "acf_bar")
There is no evidence of autocorrelation in the MCMC samples
fert.brm3 %>% mcmc_plot(type = "rhat_hist")
All Rhat values are below 1.05, suggesting the chains have converged.
neff_hist (number of effective samples): the ratio of the number of effective samples (those not rejected by the sampler) to the number of samples provides an indication of the effectiveness (and efficiency) of the MCMC sampler. Ratios that are less than 0.5 for a parameter suggest that the sampler spent considerable time in difficult areas of the sampling domain and rejected more than half of the samples (replacing them with the previous effective sample).
If the ratios are low, tightening the priors may help.
fert.brm3 %>% mcmc_plot(type = "neff_hist")
Ratios all very high.
fert.brm3 %>% mcmc_plot(type = "combo")
fert.brm3 %>% mcmc_plot(type = "violin")
The rstan package offers a range of MCMC diagnostics. Lets start with the MCMC diagnostics.
Of these, we will focus on:
fert.brm3$fit %>% stan_trace()
fert.brm3$fit %>% stan_trace(inc_warmup = TRUE)
The chains appear well mixed and very similar
fert.brm3$fit %>% stan_ac()
There is no evidence of autocorrelation in the MCMC samples
fert.brm3$fit %>% stan_rhat()
All Rhat values are below 1.05, suggesting the chains have converged.
stan_ess (number of effective samples): the ratio of the number of effective samples (those not rejected by the sampler) to the number of samples provides an indication of the effectiveness (and efficiency) of the MCMC sampler. Ratios that are less than 0.5 for a parameter suggest that the sampler spent considerable time in difficult areas of the sampling domain and rejected more than half of the samples (replacing them with the previous effective sample).
If the ratios are low, tightening the priors may help.
fert.brm3$fit %>% stan_ess()
Ratios all very high.
fert.brm3$fit %>% stan_dens(separate_chains = TRUE)
The ggmcmc package also has a set of MCMC diagnostic functions. Lets start with the MCMC diagnostics.
Of these, we will focus on:
fert.ggs <- fert.brm3$fit %>% ggs(inc_warmup = TRUE, burnin = TRUE) # does not seem to ignore burnin?
fert.ggs %>% ggs_traceplot()
fert.ggs <- fert.brm3$fit %>% ggs(inc_warmup = FALSE, burnin = TRUE) # does not seem to ignore burnin?
fert.ggs %>% ggs_traceplot()
The chains appear well mixed and very similar
fert.ggs %>% ggs_autocorrelation()
There is no evidence of autocorrelation in the MCMC samples
fert.ggs %>% ggs_Rhat()
All Rhat values are below 1.05, suggesting the chains have converged.
stan_ess (number of effective samples): the ratio of the number of effective samples (those not rejected by the sampler) to the number of samples provides an indication of the effectiveness (and efficiency) of the MCMC sampler. Ratios that are less than 0.5 for a parameter suggest that the sampler spent considerable time in difficult areas of the sampling domain and rejected more than half of the samples (replacing them with the previous effective sample).
If the ratios are low, tightening the priors may help.
fert.ggs %>% ggs_effective()
Ratios all very high.
fert.ggs %>% ggs_crosscorrelation()
fert.ggs %>% ggs_grb()
The sampling diagnostics are not relevant to INLA. Instead, we can focus on CPO and PIT
fert.inla1.cpo <- data.frame(
cpo = fert.inla1$cpo$cpo,
pit = fert.inla1$cpo$pit,
failure = fert.inla1$cpo$failure
) %>%
filter(failure == 0) %>%
mutate(row = 1:n())
g1 <- fert.inla1.cpo %>%
ggplot(aes(y = cpo, x = row)) +
geom_point()
g2 <- fert.inla1.cpo %>%
ggplot(aes(x = cpo)) +
geom_histogram()
g3 <- fert.inla1.cpo %>%
ggplot(aes(y = pit, x = row)) +
geom_point()
g4 <- fert.inla1.cpo %>%
ggplot(aes(x = pit)) +
geom_histogram()
(g1 + g2) / (g3 + g4)
Ideally, we want to see that no CPO or PIT is very different in value from any others (not the case here) and that the histograms are relatively flat (which they kind of are here - particularly considering the small amount of data).
Posterior probability checks
available_ppc()
| Package | Description | function | rstanarm | brms |
|---|---|---|---|---|
| bayesplot | Density overlay | ppc_dens_overlay |
pp_check(mod, plotfun='dens_overlay') |
pp_check(mod, type='dens_overlay') |
| Obs vs Pred error | ppc_error_scatter_avg |
pp_check(mod, plotfun='error_scatter_avg') |
pp_check(mod, type='error_scatter_avg') |
|
| Pred error vs x | ppc_error_scatter_avg_vs_x |
pp_check(mod, x=, plotfun='error_scatter_avg_vs_x') |
pp_check(mod, x=, type='error_scatter_avg_vs_x') |
|
| Preds vs x | ppc_intervals |
pp_check(mod, x=, plotfun='intervals') |
pp_check(mod, x=, type='intervals') |
|
| Partial plot | ppc_ribbon |
pp_check(mod, x=, plotfun='ribbon') |
pp_check(mod, x=, type='ribbon') |
|
Post predictive checks provide additional diagnostics about the fit of the model. Specifically, they provide a comparison between predictions drawn from the model and the observed data used to train the model.
available_ppc()
## bayesplot PPC module:
## ppc_bars
## ppc_bars_grouped
## ppc_boxplot
## ppc_data
## ppc_dens
## ppc_dens_overlay
## ppc_dens_overlay_grouped
## ppc_ecdf_overlay
## ppc_ecdf_overlay_grouped
## ppc_error_binned
## ppc_error_hist
## ppc_error_hist_grouped
## ppc_error_scatter
## ppc_error_scatter_avg
## ppc_error_scatter_avg_vs_x
## ppc_freqpoly
## ppc_freqpoly_grouped
## ppc_hist
## ppc_intervals
## ppc_intervals_data
## ppc_intervals_grouped
## ppc_km_overlay
## ppc_loo_intervals
## ppc_loo_pit
## ppc_loo_pit_data
## ppc_loo_pit_overlay
## ppc_loo_pit_qq
## ppc_loo_ribbon
## ppc_ribbon
## ppc_ribbon_data
## ppc_ribbon_grouped
## ppc_rootogram
## ppc_scatter
## ppc_scatter_avg
## ppc_scatter_avg_grouped
## ppc_stat
## ppc_stat_2d
## ppc_stat_freqpoly_grouped
## ppc_stat_grouped
## ppc_violin_grouped
pp_check(fert.rstanarm3, plotfun = "dens_overlay")
The model draws appear to be consistent with the observed data.
pp_check(fert.rstanarm3, plotfun = "error_scatter_avg")
There is no obvious pattern in the residuals.
pp_check(fert.rstanarm3, x = fert$FERTILIZER, plotfun = "error_scatter_avg_vs_x")
pp_check(fert.rstanarm3, x = fert$FERTILIZER, plotfun = "intervals")
pp_check(fert.rstanarm3, x = fert$FERTILIZER, plotfun = "ribbon")
The shinystan package allows the full suite of MCMC diagnostics and posterior predictive checks to be accessed via a web interface.
# library(shinystan)
# launch_shinystan(fert.rstanarm3)
DHARMa residuals provide very useful diagnostics. Unfortunately, we cannot directly use the simulateResiduals() function to generate the simulated residuals. However, if we are willing to calculate some of the components yourself, we can still obtain the simulated residuals from the fitted stan model.
We need to supply:
preds <- posterior_predict(fert.rstanarm3, nsamples = 250, summary = FALSE)
fert.resids <- createDHARMa(
simulatedResponse = t(preds),
observedResponse = fert$YIELD,
fittedPredictedResponse = apply(preds, 2, median),
integerResponse = "gaussian"
)
plot(fert.resids)
Conclusions:
Post predictive checks provide additional diagnostics about the fit of the model. Specifically, they provide a comparison between predictions drawn from the model and the observed data used to train the model.
available_ppc()
## bayesplot PPC module:
## ppc_bars
## ppc_bars_grouped
## ppc_boxplot
## ppc_data
## ppc_dens
## ppc_dens_overlay
## ppc_dens_overlay_grouped
## ppc_ecdf_overlay
## ppc_ecdf_overlay_grouped
## ppc_error_binned
## ppc_error_hist
## ppc_error_hist_grouped
## ppc_error_scatter
## ppc_error_scatter_avg
## ppc_error_scatter_avg_vs_x
## ppc_freqpoly
## ppc_freqpoly_grouped
## ppc_hist
## ppc_intervals
## ppc_intervals_data
## ppc_intervals_grouped
## ppc_km_overlay
## ppc_loo_intervals
## ppc_loo_pit
## ppc_loo_pit_data
## ppc_loo_pit_overlay
## ppc_loo_pit_qq
## ppc_loo_ribbon
## ppc_ribbon
## ppc_ribbon_data
## ppc_ribbon_grouped
## ppc_rootogram
## ppc_scatter
## ppc_scatter_avg
## ppc_scatter_avg_grouped
## ppc_stat
## ppc_stat_2d
## ppc_stat_freqpoly_grouped
## ppc_stat_grouped
## ppc_violin_grouped
fert.brm3 %>% pp_check(type = "dens_overlay", nsamples = 100)
The model draws appear to be consistent with the observed data.
fert.brm3 %>% pp_check(type = "error_scatter_avg")
There is no obvious pattern in the residuals.
fert.brm3 %>% pp_check(x = "FERTILIZER", type = "error_scatter_avg_vs_x")
fert.brm3 %>% pp_check(x = "FERTILIZER", type = "intervals")
pp_check(fert.brm3, x = "FERTILIZER", type = "ribbon")
The shinystan package allows the full suite of MCMC diagnostics and posterior predictive checks to be accessed via a web interface.
# library(shinystan)
# launch_shinystan(fert.brm3)
DHARMa residuals provide very useful diagnostics. Unfortunately, we cannot directly use the simulateResiduals() function to generate the simulated residuals. However, if we are willing to calculate some of the components yourself, we can still obtain the simulated residuals from the fitted stan model.
We need to supply:
preds <- fert.brm3 %>% posterior_predict(nsamples = 250, summary = FALSE)
fert.resids <- createDHARMa(
simulatedResponse = t(preds),
observedResponse = fert$YIELD,
fittedPredictedResponse = apply(preds, 2, median),
integerResponse = FALSE
)
fert.resids %>% plot()
The integerResponse argument indicates that noise will be added to the residuals such that they will become integers. This is important in for Poisson, Negative Binomial and Binomial models.
Conclusions:
INLA includes two measures of out-of-sample performace (measures of fit).
Conditional Predictive Ordinate (CPO) is the density of the observed value of \(y_i\) within the out-of-sample (\(y−i\)) posterior predictive distribution. A small CPO value associated with an observation suggests that this observation is unlikely (or surprising) in light of the model, priors and other data in the model. In addition, the sum of the CPO values (or alternatively, the negative of the mean natural logarithm of the CPO values) is a measure of fit.
fert.inla1$cpo$cpo
## [1] 0.012054491 0.012916051 0.006822433 0.008804804 0.018153179 0.018355621
## [7] 0.014801708 0.002798478 0.006057419 0.014733889
sum(fert.inla1$cpo$cop)
## [1] 0
-mean(log(fert.inla1$cpo$cpo))
## [1] 4.59101
In this case there are no CPO values that are considerably smaller (order of magnitude smaller) than the others - so with respect to the model, none of the observed values would be considered ‘surprising’. Various assumptions are made behind INLA’s computations. If any of these assumptions fail for an observation, it is flagged within (in this case) cpo$failure as a non-zero. When this is the case, it is prudent to recalculate the CPO values after removing the observations associated with failure flags not equal to zero and re-fitting the model. This can be performed using the inla.cpo() function.
fert.inla1$cpo$failure
## [1] 0 0 0 0 0 0 0 0 0 0
In this case, there are no non-zero CPO values.
Probability Integral Transforms (PIT) provides a version of CPO that is calibrated to the level of the Gaussian field so that it is clearer whether or not any of the values are ‘small’ (all values must be between 0 and 1). A histogram of PIT values that does not look approximately uniform (flat) indicates a lack of model fit.
Unfortunately, the following will not work inside of an Rmarkdown (but will work fine on the console)
plot(fert.inla1,
plot.fixed.effects = FALSE,
plot.lincomb = FALSE,
plot.random.effects = FALSE,
plot.hyperparameters = FALSE,
plot.predictor = FALSE,
plot.q = FALSE,
plot.cpo = TRUE,
plot.prior = FALSE
)
In this case the PIT values do not appear to deviate from a uniform distribution and thus do not indicate a lack of fit.
fert.inla1.cpo <- data.frame(
cpo = fert.inla1$cpo$cpo,
pit = fert.inla1$cpo$pit,
failure = fert.inla1$cpo$failure
) %>%
filter(failure == 0) %>%
mutate(row = 1:n())
g1 <- fert.inla1.cpo %>%
ggplot(aes(y = cpo, x = row)) +
geom_point()
g2 <- fert.inla1.cpo %>%
ggplot(aes(x = cpo)) +
geom_histogram()
g3 <- fert.inla1.cpo %>%
ggplot(aes(y = pit, x = row)) +
geom_point()
g4 <- fert.inla1.cpo %>%
ggplot(aes(x = pit)) +
geom_histogram()
(g1 + g2) / (g3 + g4)
Ideally, we want to see that no CPO or PIT is very different in value from any others (not the case here) and that the histograms are relatively flat (which they kind of are here - particularly considering the small amount of data).
In the following, the top left is the distribution of residuals and top right is the observed vs predicted values.
ggplot_inla_residuals(fert.inla1, observed = fert$YIELD)
Conclusions-
The following figure represents the equivalent of a (standardised) residual plot.
ggplot_inla_residuals2(fert.inla1, observed = fert$YIELD)
Unfortunately, DHARMa does not directly support INLA. Therefore, in order to make use of this framework, we need to do some of the heavy lifting. Specifically, we need to generate the posterior predictions associated with the observed data.
Whilst we can draw random samples from the posterior with the inla.posterior.sample() function, this will only account for uncertainty in the fixed parameter estimates. That is, it will not incorporate the overall uncertainty in the Gaussian distribution (\(\sigma\)). Therefore, we need to add this back on ourself (keep in mind that this will be in units of precision and thus needs to be back-scaled into units of standard deviation). Furthermore, we will need to use the estimates of standard deviation to estimate the random noise to add onto the predictions. This is done by resampling the family (Gaussian in this case).
I acknowledge that this (resampling the SD) appears to be a bit of a hack and seems to go against the INLA principles. Nevertheless, we are only doing this this for the purposes of checking residual diagnostics.
## draw 250 samples from the posterior
draws <- inla.posterior.sample(n = 250, result = fert.inla)
## extract the latent predictions for the observed data
preds <- t(sapply(draws, function(x) x$latent[1:nrow(fert)]))
## extract the first (family precision) hyperprior
preds.hyper <- sapply(draws, function(x) 1 / sqrt(x$hyperpar[[1]]))
## use this to generate gaussian noise
preds.hyper <- rnorm(length(preds.hyper), mean = 0, sd = preds.hyper)
## add the noise to each prediction
preds <- sweep(preds, 1, preds.hyper, FUN = "+")
## generate the DHARMa residuals
fert.resids <- createDHARMa(
simulatedResponse = t(preds),
observedResponse = fert$YIELD,
fittedPredictedResponse = apply(preds, 2, median),
integerResponse = FALSE
)
fert.resids %>% plot()
Conclusions:
fert.rstanarm3 %>%
ggpredict() %>%
plot(add.data = TRUE)
## $FERTILIZER
fert.rstanarm3 %>%
ggemmeans(~FERTILIZER) %>%
plot(add.data = TRUE)
fert.rstanarm3 %>%
fitted_draws(newdata = fert) %>%
median_hdci() %>%
ggplot(aes(x = FERTILIZER, y = .value)) +
geom_ribbon(aes(ymin = .lower, ymax = .upper), fill = "blue", alpha = 0.3) +
geom_line()
fert.brm3 %>%
ggemmeans(~FERTILIZER) %>%
plot(add.data = TRUE)
fert.brm3 %>% conditional_effects()
fert.brm3 %>%
conditional_effects() %>%
plot(points = TRUE)
fert.brm3 %>%
conditional_effects(spaghetti = TRUE, nsamples = 200) %>%
plot(points = TRUE)
fert.brm3 %>%
ggpredict() %>%
plot(add.data = TRUE)
## $FERTILIZER
fert.brm3 %>%
ggemmeans(~FERTILIZER) %>%
plot(add.data = TRUE)
fert.brm3 %>%
fitted_draws(newdata = fert) %>%
median_hdci() %>%
ggplot(aes(x = FERTILIZER, y = .value)) +
geom_ribbon(aes(ymin = .lower, ymax = .upper), fill = "blue", alpha = 0.3) +
geom_line()
plot(fert.inla1,
plot.fixed.effects = FALSE,
plot.lincomb = FALSE,
plot.random.effects = FALSE,
plot.hyperparameters = FALSE,
plot.predictor = TRUE,
plot.q = FALSE,
plot.cpo = FALSE,
plot.prior = FALSE
)
newdata <- fert %>% tidyr::expand(FERTILIZER = modelr::seq_range(FERTILIZER, n = 100))
Xmat <- model.matrix(~FERTILIZER, newdata)
nms <- colnames(fert.inla1$model.matrix)
n <- sapply(nms, function(x) 0, simplify = FALSE)
draws <- inla.posterior.sample(n = 250, result = fert.inla1, selection = n)
coefs <- t(sapply(draws, function(x) x$latent))
Fit <- coefs %*% t(Xmat) %>%
as.data.frame() %>%
mutate(Rep = 1:n()) %>%
pivot_longer(cols = -Rep) %>%
group_by(name) %>%
median_hdci(value) %>%
ungroup() %>%
mutate(name = as.integer(as.character(name))) %>%
arrange(name)
newdata <- newdata %>%
bind_cols(Fit)
newdata %>%
ggplot(aes(x = FERTILIZER)) +
geom_ribbon(aes(ymin = .lower, ymax = .upper), fill = "orange", color = NA, alpha = 0.3) +
geom_line(aes(y = value), color = "orange") +
geom_point(data = fert, aes(y = YIELD)) +
theme_classic()
Rather than simply return point estimates of each of the model parameters, Bayesian analyses capture the full posterior of each parameter. These are typically stored within the list structure of the output object.
As with most statistical routines, the overloaded summary() function provides an overall summary of the model parameters. Typically, the summaries will include the means / medians along with credibility intervals and perhaps convergence diagnostics (such as R hat). However, more thorough investigation and analysis of the parameter posteriors requires access to the full posteriors.
There is currently a plethora of functions for extracting the full posteriors from models. In part, this is a reflection of a rapidly evolving space with numerous packages providing near equivalent functionality (it should also be noted, that over time, many of the functions have been deprecated due to inconsistencies in their names). Broadly speaking, the functions focus on draws from the posterior of either the parameters (intercept, slope, standard deviation etc), linear predictor, expected values or predicted values. The distinction between the latter three are highlighted in the following table.
| Property | Description |
|---|---|
| linear predictors | values predicted on the link scale |
| expected values | predictions (on response scale) without residual error (predicting expected mean outcome(s)) |
| predicted values | predictions (on response scale) that incorporate residual error |
| fitted values | predictions on the response scale |
The following table lists the various ways of extracting the full posteriors of the model parameters parameters, expected values and predicted values. The crossed out items are now deprecated and function with a namespace of __ mean that the functionality is provided via a range of packages.
| Function | Values | Description |
|---|---|---|
__::as.matrix() |
Parameters | Returns \(n\times p\) matrix |
__::as.data.frame() |
Parameters | Returns \(n\times p\) data.frame |
__::as_tibble() |
Parameters | Returns \(n\times p\) tibble |
posterior::as_draws_df() |
Parameters | Returns \(n\times p\) data.frame with additional info about chain, interaction and draw |
brms::posterior_samples() |
||
tidybayes::tidy_draws() |
Parameters | Returns \(n\times p\) tibble with addition info about the chain, iteration and draw |
rstan::extract() |
Parameters | Returns a \(p\) length list of \(n\) length vectors |
tidybayes::spread_draws() |
Parameters | Returns \(n\times r\) tibble with additional info about chain, interaction and draw |
tidybayes::gather_draws() |
Parameters | Returns a gathered spread_draws tibble with additional info about chain, interaction and draw |
rstanarm::posterior_linpred() |
Linear predictors | Returns \(n\times N\) tibble on the link scale |
brms::posterior_linpred() |
Linear predictors | Returns \(n\times N\) tibble on the link scale |
tidybayes::linpred_draws() |
Linear predictors | Returns tibble with $nN rows and .linpred on the link scale additional info about chain, interaction and draw |
rstanarm::posterior_epred() |
Expected values | Returns \(n\times N\) tibble on the response scale |
brms::posterior_epred() |
Expected values | Returns \(n\times N\) tibble on the response scale |
tidybayes::epred_draws() |
Expected values | Returns tibble with $nN rows and .epred on the response scale additional info about chain, interaction and draw |
rstanarm::posterior_predict() |
Expected values | Returns \(n\times N\) tibble of predictions (including residuals) on the response scale |
brms::posterior_predict() |
Expected values | Returns \(n\times N\) tibble of predictions (including residuals) on the response scale |
tidybayes::predicted_draws() |
Expected values | Returns tibble with $nN rows and .prediction (including residuals) on the response scale additional info about chain, interaction and draw |
where \(n\) is the number of MCMC samples and \(p\) is the number of parameters to estimate, \(N\) is the number of newdata rows and \(r\) is the number of requested parameters. For the tidybayes versions in the table above, the function expects a model to be the first parameter (and a dataframe to be the second). There are also add_ versions which expect a dataframe to be the first argument and the model to be the second. These alternatives facilitate pipings with different starting objects.
| Function | Description |
|---|---|
median_qi |
Median and quantiles of specific columns |
median_hdi |
Median and Highest Probability Density Interval of specific columns |
median_hdci |
Median and continuous Highest Probability Density Interval of specific columns |
tidyMCMC |
Median/mean and quantiles/hpd of all columns |
It is important to remember that when working with Bayesian models, everything is a distribution. Whilst point estimates (such as a mean) of the parameters can be calculated from these distributions, we start off with a large number of estimates per parameter.
rstanarm captures the MCMC samples from stan within the returned list. There are numerous ways to retrieve and summarise these samples. The first three provide convenient numeric summaries from which you can draw conclusions, the last four provide ways of obtaining the full posteriors.
The summary() method generates simple summaries (mean, standard deviation as well as 10, 50 and 90 percentiles).
fert.rstanarm3 %>% summary()
##
## Model Info:
## function: stan_glm
## family: gaussian [identity]
## formula: YIELD ~ FERTILIZER
## algorithm: sampling
## sample: 2400 (posterior sample size)
## priors: see help('prior_summary')
## observations: 10
## predictors: 2
##
## Estimates:
## mean sd 10% 50% 90%
## (Intercept) 52.6 12.7 37.1 52.7 68.1
## FERTILIZER 0.8 0.1 0.7 0.8 0.9
## sigma 19.1 4.9 13.8 18.2 25.6
##
## Fit Diagnostics:
## mean sd 10% 50% 90%
## mean_PPD 163.4 8.2 153.4 163.5 173.6
##
## The mean_ppd is the sample average posterior predictive distribution of the outcome variable (for details see help('summary.stanreg')).
##
## MCMC diagnostics
## mcse Rhat n_eff
## (Intercept) 0.3 1.0 2358
## FERTILIZER 0.0 1.0 2310
## sigma 0.1 1.0 2360
## mean_PPD 0.2 1.0 2253
## log-posterior 0.0 1.0 1978
##
## For each parameter, mcse is Monte Carlo standard error, n_eff is a crude measure of effective sample size, and Rhat is the potential scale reduction factor on split chains (at convergence Rhat=1).
Conclusions:
tidyMCMC(fert.rstanarm3$stanfit,
estimate.method = "median", conf.int = TRUE,
conf.method = "HPDinterval", rhat = TRUE, ess = TRUE
)
Conclusions:
fert.rstanarm3$stanfit %>% as_draws_df()
fert.rstanarm3$stanfit %>%
as_draws_df() %>%
summarise_draws(
"median",
~ HDInterval::hdi(.x),
"rhat",
"ess_bulk"
)
This is purely a graphical depiction on the posteriors.
fert.rstanarm3 %>% tidy_draws()
fert.draw <- fert.rstanarm3 %>% gather_draws(`(Intercept)`, FERTILIZER, sigma)
## OR via regex
fert.draw <- fert.rstanarm3 %>% gather_draws(`.Intercept.*|FERT.*|sigma`, regex = TRUE)
fert.draw
We can then summarise this
fert.draw %>% median_hdci()
fert.rstanarm3 %>%
gather_draws(`(Intercept)`, FERTILIZER, sigma) %>%
ggplot() +
stat_halfeye(aes(x = .value, y = .variable)) +
facet_wrap(~.variable, scales = "free")
Conclusions:
fert.rstanarm3 %>% plot(plotfun = "mcmc_intervals")
fert.rstanarm3 %>% spread_draws(`(Intercept)`, FERTILIZER, sigma)
# OR via regex
fert.rstanarm3 %>% spread_draws(`.Intercept.*|FERT.*|sigma`, regex = TRUE)
Note, this is not deprecated
fert.rstanarm3 %>%
posterior_samples() %>%
as_tibble()
fert.rstanarm3 %>%
bayes_R2() %>%
median_hdci()
It is possible to obtain an empirical p-value (for those that cannot live without p-values). This is essentially compares (for any posterior) that the mean is zero compared to a multivariate distribution with elliptical contours.
mcmcpvalue <- function(samp) {
## elementary version that creates an empirical p-value for the
## hypothesis that the columns of samp have mean zero versus a
## general multivariate distribution with elliptical contours.
## differences from the mean standardized by the observed
## variance-covariance factor
## Note, I put in the bit for single terms
if (length(dim(samp)) == 0) {
std <- backsolve(chol(var(samp)), cbind(0, t(samp)) - mean(samp), transpose = TRUE)
sqdist <- colSums(std * std)
sum(sqdist[-1] > sqdist[1]) / length(samp)
} else {
std <- backsolve(chol(var(samp)), cbind(0, t(samp)) - colMeans(samp), transpose = TRUE)
sqdist <- colSums(std * std)
sum(sqdist[-1] > sqdist[1]) / nrow(samp)
}
}
mcmcpvalue(as.matrix(fert.rstanarm3)[, c("FERTILIZER")])
## [1] 0
brms captures the MCMC samples from stan within the returned list. There are numerous ways to retrieve and summarise these samples. The first three provide convenient numeric summaries from which you can draw conclusions, the last four provide ways of obtaining the full posteriors.
The summary() method generates simple summaries (mean, standard deviation as well as 10, 50 and 90 percentiles).
fert.brm3 %>% summary()
## Family: gaussian
## Links: mu = identity; sigma = identity
## Formula: YIELD ~ FERTILIZER
## Data: fert (Number of observations: 10)
## Draws: 3 chains, each with iter = 1000; warmup = 200; thin = 5;
## total post-warmup draws = 480
##
## Population-Level Effects:
## Estimate Est.Error l-95% CI u-95% CI Rhat Bulk_ESS Tail_ESS
## Intercept 52.69 8.91 35.26 70.79 1.00 2336 2188
## FERTILIZER 0.81 0.06 0.69 0.92 1.00 2320 2326
##
## Family Specific Parameters:
## Estimate Est.Error l-95% CI u-95% CI Rhat Bulk_ESS Tail_ESS
## sigma 12.75 1.85 9.60 16.85 1.00 2194 2291
##
## Draws were sampled using sampling(NUTS). For each parameter, Bulk_ESS
## and Tail_ESS are effective sample size measures, and Rhat is the potential
## scale reduction factor on split chains (at convergence, Rhat = 1).
Conclusions:
fert.brm3$fit %>%
tidyMCMC(
estimate.method = "median",
conf.int = TRUE,
conf.method = "HPDinterval",
rhat = TRUE, ess = TRUE
)
Conclusions:
fert.brm3 %>% as_draws_df()
Return the draws (samples) for each parameter in wide format
fert.brm3 %>% tidy_draws()
The above can be useful for exploring the full posteriors of all the parameters of performing specific calculations using the posteriors, summarising the parameters takes a few more steps.
fert.brm3 %>%
tidy_draws() %>%
gather_variables() %>%
median_hdci()
The gather_draws on the other hand, conveniently combines tidy_draws and gather_variables together in a single command. Furthermore, it returns all of the variables. The spread_draws function allows users to target specific variables (either by naming them in full or via regexp).
fert.brm3 %>% get_variables()
## [1] "b_Intercept" "b_FERTILIZER" "sigma" "prior_Intercept"
## [5] "prior_b" "prior_sigma" "lp__" "accept_stat__"
## [9] "stepsize__" "treedepth__" "n_leapfrog__" "divergent__"
## [13] "energy__"
fert.brm3 %>%
gather_draws(b_Intercept, b_FERTILIZER, sigma) %>%
median_hdci()
## OR via regex
fert.brm3 %>%
gather_draws(`b_.*|sigma`, regex = TRUE) %>%
median_hdci()
fert.brm3 %>%
gather_draws(b_Intercept, b_FERTILIZER, sigma) %>%
ggplot() +
stat_halfeye(aes(x = .value, y = .variable)) +
facet_wrap(~.variable, scales = "free")
fert.brm3 %>%
gather_draws(b_Intercept, b_FERTILIZER, sigma) %>%
ggplot() +
stat_halfeye(aes(x = .value, y = .variable))
Conclusions:
Select just the parameters of interest.
fert.brm3 %>% spread_draws(b_Intercept, b_FERTILIZER, sigma)
# OR via regex
fert.brm3 %>% spread_draws(`b_.*|sigma`, regex = TRUE)
fert.brm3 %>% mcmc_plot(type = "intervals")
Note, this is now deprecated
fert.brm3 %>%
posterior_samples() %>%
as_tibble()
fert.brm3 %>%
bayes_R2(summary = FALSE) %>%
median_hdci()
It is possible to obtain an empirical p-value (for those that cannot live without p-values). This is essentially compares (for any posterior) that the mean is zero compared to a multivariate distribution with elliptical contours.
mcmcpvalue <- function(samp) {
## elementary version that creates an empirical p-value for the
## hypothesis that the columns of samp have mean zero versus a
## general multivariate distribution with elliptical contours.
## differences from the mean standardized by the observed
## variance-covariance factor
## Note, I put in the bit for single terms
if (length(dim(samp)) == 0) {
std <- backsolve(chol(var(samp)), cbind(0, t(samp)) - mean(samp), transpose = TRUE)
sqdist <- colSums(std * std)
sum(sqdist[-1] > sqdist[1]) / length(samp)
} else {
std <- backsolve(chol(var(samp)), cbind(0, t(samp)) - colMeans(samp), transpose = TRUE)
sqdist <- colSums(std * std)
sum(sqdist[-1] > sqdist[1]) / nrow(samp)
}
}
mcmcpvalue(as.matrix(fert.brm3)[, c("b_FERTILIZER")])
## [1] 0
INLA captures a summary of the parameter posteriors within the fitted object.
The summary() method generates simple summaries (mean, standard deviation as well as 10, 50 and 90 percentiles).
fert.inla1 %>% summary()
##
## Call:
## c("inla(formula = YIELD ~ FERTILIZER, family = \"gaussian\", data =
## fert, ", " control.compute = list(config = TRUE, dic = TRUE, waic =
## TRUE, ", " cpo = TRUE), control.family = list(hyper = list(prec =
## list(prior = \"loggamma\", ", " param = c(0.5, 0.31)))), control.fixed
## = list(mean.intercept = 80, ", " prec.intercept = 1e-05, mean = 0, prec
## = 0.0384))")
## Time used:
## Pre = 0.523, Running = 0.0683, Post = 0.0392, Total = 0.631
## Fixed effects:
## mean sd 0.025quant 0.5quant 0.975quant mode kld
## (Intercept) 52.023 13.981 24.003 52.011 80.068 51.996 0
## FERTILIZER 0.811 0.090 0.630 0.811 0.991 0.811 0
##
## Model hyperparameters:
## mean sd 0.025quant 0.5quant
## Precision for the Gaussian observations 0.003 0.001 0.001 0.003
## 0.975quant mode
## Precision for the Gaussian observations 0.007 0.002
##
## Expected number of effective parameters(stdev): 2.00(0.002)
## Number of equivalent replicates : 5.01
##
## Deviance Information Criterion (DIC) ...............: 91.62
## Deviance Information Criterion (DIC, saturated) ....: 14.69
## Effective number of parameters .....................: 3.21
##
## Watanabe-Akaike information criterion (WAIC) ...: 91.36
## Effective number of parameters .................: 2.49
##
## Marginal log-Likelihood: -54.83
## CPO and PIT are computed
##
## Posterior marginals for the linear predictor and
## the fitted values are computed
Conclusions:
brinla::bri.fixed.plot(fert.inla1)
brinla::bri.hyperpar.plot(fert.inla1)
Since INLA is a Bayesian approximation, unlike full Bayesian methods, there are not chains of posterior draws. However, we can use the inla.posterior.sample() function, to generate draws of parameter and fitted value posteriors from the fitted model. In the following code snippet, we will generate 1000 draws from the fitted model (for repeatability, I will also set a random seed).
The output of this function is a list and items are packed in according to the sample (draw) number. I find this awkward to work with and prefer to have the data organised by parameters. However, prior to reorganising the list, I will query the latent (fixed and fitted values) parameter names to help with filtering to just the ones I am interested in later on.
## Get all the draws as a list
n <- 1000
draws <- inla.posterior.sample(n = n, result = fert.inla1, seed = 1)
## Redimension the list for the latent (fixed and fitted) values
(latent.names <- draws[[1]]$latent %>% rownames())
## [1] "Predictor:1" "Predictor:2" "Predictor:3" "Predictor:4"
## [5] "Predictor:5" "Predictor:6" "Predictor:7" "Predictor:8"
## [9] "Predictor:9" "Predictor:10" "(Intercept):1" "FERTILIZER:1"
The names that begin with Predictor: are the fitted values. Essentially, they are the estimated predicted values associated with the observed data. The (Intercept):1 and FERTILIZER:1 are the intercept and slope respectively.
Now to convert the list of draws into a data.frame.
draws <- sapply(draws, function(x) x[["latent"]]) %>%
as.data.frame() %>%
set_names(paste0("Draw", 1:n)) %>%
mutate(Parameter = latent.names) %>%
dplyr::select(Parameter, everything())
draws
This will convert the list into a \(s\times p\) data.frame, where \(s\) is the number of draws (1000 in this case) and \(p\) is the number of latent parameters (12 in this case) plus an additional column to keep track of the Parameters.
Finally, we might like to lengthen this data set for more convenient plotting and summarising.
fert.draws <- draws %>% pivot_longer(cols = -Parameter, names_to = "Draws")
fert.draws
To focus on and filter to just the fixed effects, we could now:
fert.draws %>%
filter(grepl("Intercept|FERTILIZER", Parameter)) %>%
group_by(Parameter) %>%
median_hdci(value)
fert.draws %>%
filter(grepl("Intercept|FERTILIZER", Parameter)) %>%
ggplot(aes(x = value, y = Parameter)) +
geom_vline(xintercept = 0, linetype = "dashed") +
stat_pointinterval(point_interval = median_hdci)
## or separate into panels
fert.draws %>%
filter(grepl("Intercept|FERTILIZER", Parameter)) %>%
ggplot(aes(x = value)) +
geom_vline(xintercept = 0) +
stat_pointinterval(point_interval = median_hdci) +
facet_grid(~Parameter, scales = "free_x")
fert.draws %>%
filter(grepl("Intercept|FERTILIZER", Parameter)) %>%
group_by(Parameter) %>%
nest() %>%
mutate(
hpd = map(data, ~ median_hdci(.x$value)),
Density = map(data, function(.x) {
d <- density(.x$value)
data.frame(x = d$x, y = d$y)
}),
Quant = map2(Density, hpd, ~ factor(findInterval(.x$x, .y[, c("ymin", "ymax")])))
) %>%
unnest(c(Density, Quant)) %>%
ggplot(aes(x = x, y = y, fill = Quant)) +
geom_vline(xintercept = 0) +
geom_ribbon(aes(ymin = 0, ymax = y)) +
facet_wrap(~Parameter, scales = "free")
fert.draws %>%
filter(grepl("Intercept|FERTILIZER", Parameter)) %>%
ggplot(aes(x = value, y = Parameter, fill = stat(quantile))) +
geom_vline(xintercept = 0, linetype = "dashed") +
ggridges::stat_density_ridges(
geom = "density_ridges_gradient",
calc_ecdf = TRUE,
quantile_fun = function(x, probs) quantile(x, probs),
quantiles = c(0.025, 0.975)
) +
scale_fill_viridis_d()
fert.draws %>%
filter(grepl("Intercept|FERTILIZER", Parameter)) %>%
ggplot(aes(x = value, y = Parameter, fill = stat(quantile))) +
geom_vline(xintercept = 0, linetype = "dashed") +
ggridges::stat_density_ridges(
geom = "density_ridges_gradient",
calc_ecdf = TRUE,
quantile_fun = function(x, probs) quantile(x, probs),
quantiles = c(0.025, 0.975)
) +
scale_fill_viridis_d() +
facet_grid(~Parameter, scales = "free_x")
cor(
fert.inla1$summary.fitted.values[, "mean"],
fert$YIELD
)^2
## [1] 0.9216005
There are a large number of candidate routines for performing prediction. We will go through many of these. It is worth noting that prediction is technically the act of estimating what we expect to get if we were to collect a single new observation from a particular population (e.g. a specific level of fertilizer concentration). Often this is not what we want. Often we want the fitted values - estimates of what we expect to get if we were to collect multiple new observations and average them.
So while fitted values represent the expected underlying processes occurring in the system, predicted values represent our expectations from sampling from such processes.
| Package | Function | Description | Summarise with |
|---|---|---|---|
rstantools |
posterior_predict |
Draw from the posterior of a prediction (includes sigma) - predicts single observations | tidyMCMC() |
rstantools |
posterior_linpred |
Draw from the posterior of the fitted values (on the link scale) - predicts average observations | tidyMCMC() |
rstantools |
posterior_epred |
Draw from the posterior of the fitted values (on the response scale) - predicts average observations | tidyMCMC() |
tidybayes |
predicted_draws |
Extract the posterior of prediction values | median_hdci() |
tidybayes |
epred_draws |
Extract the posterior of expected values | median_hdci() |
tidybayes |
fitted_draws |
median_hdci() |
|
tidybayes |
add_predicted_draws |
Adds draws from the posterior of predictions to a data frame (of prediction data) | median_hdci() |
tidybayes |
add_fitted_draws |
Adds draws from the posterior of fitted values to a data frame (of prediction data) | median_hdci() |
emmeans |
emmeans |
Estimated marginal means from which posteriors can be drawn (via tidy_draws |
median_hdci() |
For simple models prediction is essentially taking the model formula complete with parameter (coefficient) estimates and solving for new values of the predictor. To explore this, we will use the fitted model to predict Yield for a Fertilizer concentration of 110.
We will therefore start by establishing this prediction domain as a data frame to use across all of the prediction routines.
## establish a data set that defines the new data to predict against
newdata <- data.frame(FERTILIZER = 110)
fert.rstanarm3 %>% emmeans(~FERTILIZER, at = newdata)
## FERTILIZER emmean lower.HPD upper.HPD
## 110 141 130 152
##
## Point estimate displayed: median
## HPD interval probability: 0.95
fert.rstanarm3 %>%
tidybayes::predicted_draws(newdata) %>%
median_hdci()
## or
newdata %>%
tidybayes::add_predicted_draws(fert.rstanarm3) %>%
median_hdci()
## or
fert.rstanarm3 %>%
posterior_predict(newdata = newdata) %>%
tidyMCMC(estimate.method = "median", conf.int = TRUE, conf.method = "HPDinterval")
fert.rstanarm3 %>%
epred_draws(newdata) %>%
median_hdci()
## or
newdata %>%
add_epred_draws(fert.rstanarm3) %>%
median_hdci()
## or
fert.rstanarm3 %>%
posterior_epred(newdata = newdata) %>%
tidyMCMC(estimate.method = "median", conf.int = TRUE, conf.method = "HPDinterval")
fert.rstanarm3 %>%
linpred_draws(newdata) %>%
median_hdci()
## or
newdata %>%
add_linpred_draws(fert.rstanarm3) %>%
median_hdci()
## or
fert.rstanarm3 %>%
posterior_linpred(newdata = newdata) %>%
tidyMCMC(estimate.method = "median", conf.int = TRUE, conf.method = "HPDinterval")
## Establish an appropriate model matrix
Xmat <- model.matrix(~FERTILIZER, data = newdata)
### get the posterior draws for the linear predictor
coefs <- fert.rstanarm3$stanfit %>%
as_draws_df() %>%
dplyr::select(c("(Intercept)", "FERTILIZER")) %>%
as.matrix()
fit <- coefs %*% t(Xmat)
fit %>% median_hdci()
## or
coefs <- fert.rstanarm3 %>%
tidy_draws() %>%
dplyr::select(c("(Intercept)", "FERTILIZER")) %>%
as.matrix()
fit <- coefs %*% t(Xmat)
fit %>% median_hdci()
## or
coefs <- fert.rstanarm3$stanfit %>%
as_draws_matrix() %>%
subset_draws(c("(Intercept)", "FERTILIZER"))
fit <- coefs %*% t(Xmat)
fit %>% median_hdci()
This is the option we will focus on for most of the worksheets
fert.brm3 %>%
emmeans(~FERTILIZER, at = newdata)
## FERTILIZER emmean lower.HPD upper.HPD
## 110 141 133 149
##
## Point estimate displayed: median
## HPD interval probability: 0.95
## OR
fert.brm3 %>%
emmeans(~FERTILIZER, at = newdata) %>%
tidy_draws() %>%
median_hdci()
fert.brm3 %>%
tidybayes::predicted_draws(newdata) %>%
median_hdci()
## or
newdata %>%
tidybayes::add_predicted_draws(fert.brm3) %>%
median_hdci()
## or
fert.brm3 %>%
posterior_predict(newdata = newdata) %>%
as.mcmc() %>%
tidyMCMC(estimate.method = "median", conf.int = TRUE, conf.method = "HPDinterval")
fert.brm3 %>%
epred_draws(newdata) %>%
median_hdci()
## or
newdata %>%
add_epred_draws(fert.brm3) %>%
median_hdci()
## or
fert.brm3 %>%
posterior_epred(newdata = newdata) %>%
as.mcmc() %>%
tidyMCMC(estimate.method = "median", conf.int = TRUE, conf.method = "HPDinterval")
fert.brm3 %>%
linpred_draws(newdata) %>%
median_hdci()
## or
newdata %>%
add_linpred_draws(fert.brm3) %>%
median_hdci()
## or
fert.brm3 %>%
posterior_linpred(newdata = newdata) %>%
as.mcmc() %>%
tidyMCMC(estimate.method = "median", conf.int = TRUE, conf.method = "HPDinterval")
## Establish an appropriate model matrix
Xmat <- model.matrix(~FERTILIZER, data = newdata)
### get the posterior draws for the linear predictor
coefs <- fert.brm3 %>%
as_draws_df() %>%
dplyr::select(c("b_Intercept", "b_FERTILIZER")) %>%
as.matrix()
fit <- coefs %*% t(Xmat)
fit %>%
median_hdci() %>%
bind_cols(newdata)
## or
coefs <- fert.brm3 %>%
tidy_draws() %>%
dplyr::select(c("b_Intercept", "b_FERTILIZER")) %>%
as.matrix()
fit <- coefs %*% t(Xmat)
fit %>%
median_hdci() %>%
bind_cols(newdata)
## or
coefs <- fert.brm3 %>%
as_draws_matrix() %>%
subset_draws(c("b_Intercept", "b_FERTILIZER"))
fit <- coefs %*% t(Xmat)
fit %>%
median_hdci() %>%
bind_cols(newdata)
## or
## Establish an appropriate model matrix
Xmat <- model.matrix(~FERTILIZER, data = newdata)
### get the posterior draws for the linear predictor
coefs <- fert.brm3 %>%
posterior_samples(pars = c("b_Intercept", "b_FERTILIZER")) %>%
as.matrix()
fit <- coefs %*% t(Xmat)
fit %>%
median_hdci() %>%
bind_cols(newdata)
As with most things to do with INLA, things are done a little differently. In INLA, there are three options for predictions:
NA.Lets explore each of these in turn.
## Expected values
Xmat <- model.matrix(~FERTILIZER, newdata)
nms <- colnames(fert.inla1$model.matrix)
sel <- sapply(nms, function(x) 0, simplify = FALSE)
n <- 1000
draws <- inla.posterior.sample(n = n, result = fert.inla1, selection = sel, seed = 1)
coefs <- t(sapply(draws, function(x) x$latent))
Fit <- coefs %*% t(Xmat) %>%
as.data.frame() %>%
mutate(Rep = 1:n()) %>%
pivot_longer(cols = -Rep) %>%
group_by(name) %>%
median_hdci(value) %>%
ungroup() %>%
mutate(name = as.integer(as.character(name))) %>%
arrange(name)
newdata.inla <- newdata %>%
bind_cols(Fit)
newdata.inla
## Predictions
Fit <- coefs %*% t(Xmat)
draws <- inla.posterior.sample(n = n, result = fert.inla1, seed = 1)
sigma <- sqrt(1 / (sapply(draws, function(x) x$hyperpar)))
sigma <- sapply(sigma, function(x) rnorm(1, 0, sigma))
Fit <- sweep(Fit, MARGIN = 1, sigma, FUN = "+") %>%
as.data.frame() %>%
mutate(Rep = 1:n()) %>%
pivot_longer(cols = -Rep) %>%
group_by(name) %>%
median_hdci(value) %>%
bind_cols(newdata) %>%
ungroup() %>%
dplyr::select(FERTILIZER, everything(), -name)
Fit
## or
fun <- function(coefs = NA) {
## theta[1] is the precision
return(Intercept + FERTILIZER * coefs[, "FERTILIZER"] +
rnorm(nrow(coefs), sd = sqrt(1 / theta[1])))
}
Fit <- inla.posterior.sample.eval(fun, draws, coefs = newdata) %>%
as.data.frame() %>%
bind_cols(newdata) %>%
pivot_longer(cols = -FERTILIZER) %>%
group_by(FERTILIZER) %>%
median_hdci(value)
Fit
fert.pred <- fert %>%
bind_rows(newdata)
i.newdata <- (nrow(fert) + 1):nrow(fert.pred)
fert.inla2 <- inla(YIELD ~ FERTILIZER,
data = fert.pred,
family = "gaussian",
control.fixed = list(
mean.intercept = 80,
prec.intercept = 0.00001,
mean = 0,
prec = 0.0384
),
control.family = list(hyper = list(prec = list(
prior = "loggamma",
param = c(0.5, 0.31)
))),
control.compute = list(config = TRUE, dic = TRUE, waic = TRUE, cpo = TRUE)
)
fert.inla2$summary.fitted.values[i.newdata, ]
## or on the link scale...
fert.inla2$summary.linear.predictor[i.newdata, ]
Xmat <- model.matrix(~FERTILIZER, data = newdata)
lincomb <- inla.make.lincombs(as.data.frame(Xmat))
fert.inla3 <- inla(YIELD ~ FERTILIZER,
data = fert,
family = "gaussian",
lincomb = lincomb,
control.fixed = list(
mean.intercept = 80,
prec.intercept = 0.00001,
mean = 0,
prec = 0.0384
),
control.family = list(hyper = list(prec = list(
prior = "loggamma",
param = c(0.5, 0.31)
))),
control.compute = list(config = TRUE, dic = TRUE, waic = TRUE, cpo = TRUE)
)
fert.inla3$summary.lincomb.derived
Since we have the entire posterior, we are able to make probability statements. We simply count up the number of MCMC sample draws that satisfy a condition (e.g represent a slope greater than 0) and then divide by the total number of MCMC samples.
For this exercise, we will explore the following:
fert.rstanarm3 %>% hypothesis("FERTILIZER>0")
## Hypothesis Tests for class :
## Hypothesis Estimate Est.Error CI.Lower CI.Upper Evid.Ratio Post.Prob
## 1 (FERTILIZER) > 0 0.81 0.09 0.67 0.95 Inf 1
## Star
## 1 *
## ---
## 'CI': 90%-CI for one-sided and 95%-CI for two-sided hypotheses.
## '*': For one-sided hypotheses, the posterior probability exceeds 95%;
## for two-sided hypotheses, the value tested against lies outside the 95%-CI.
## Posterior probabilities of point hypotheses assume equal prior probabilities.
Conclusions:
Alternatively…
fert.rstanarm3 %>%
tidy_draws() %>%
summarise(P = sum(FERTILIZER > 0) / n())
## # A tibble: 1 × 1
## P
## <dbl>
## 1 1
Conclusions:
newdata <- list(FERTILIZER = c(200, 100))
fert.rstanarm3 %>%
emmeans(~FERTILIZER, at = newdata) %>%
pairs()
## contrast estimate lower.HPD upper.HPD
## 200 - 100 80.8 62.9 96.8
##
## Point estimate displayed: median
## HPD interval probability: 0.95
Conclusions:
If we want to derive other properties, such as the percentage change, then we use tidy_draws() and then simple tidyverse spreadsheet operation.
fert.mcmc <- fert.rstanarm3 %>%
emmeans(~FERTILIZER, at = newdata) %>%
tidy_draws() %>%
rename_with(~ str_replace(., "FERTILIZER ", "p")) %>%
mutate(
Eff = p200 - p100,
PEff = 100 * Eff / p100
)
fert.mcmc %>% head()
Now we can calculate the medians and HPD intervals of each column (and ignore the .chain, .iteration and .draw).
fert.mcmc %>% tidyMCMC(
estimate.method = "median",
conf.int = TRUE, conf.method = "HPDinterval"
)
Alternatively, we could use median_hdci
fert.mcmc %>% median_hdci(PEff)
Conclusions:
To get the probability that the effect is greater than a 50% increase.
fert.mcmc %>% summarise(P = sum(PEff > 50) / n())
## # A tibble: 1 × 1
## P
## <dbl>
## 1 0.919
Conclusions:
Finally, we could alternatively use hypothesis(). Note that when we do so, the estimate is the difference between the effect and the hypothesised effect (50%).
fert.mcmc %>% hypothesis("PEff>50")
## Hypothesis Tests for class :
## Hypothesis Estimate Est.Error CI.Lower CI.Upper Evid.Ratio Post.Prob
## 1 (PEff)-(50) > 0 10.82 8.28 -1.67 24.71 11.37 0.92
## Star
## 1
## ---
## 'CI': 90%-CI for one-sided and 95%-CI for two-sided hypotheses.
## '*': For one-sided hypotheses, the posterior probability exceeds 95%;
## for two-sided hypotheses, the value tested against lies outside the 95%-CI.
## Posterior probabilities of point hypotheses assume equal prior probabilities.
fert.brm3 %>% hypothesis("FERTILIZER > 0")
## Hypothesis Tests for class b:
## Hypothesis Estimate Est.Error CI.Lower CI.Upper Evid.Ratio Post.Prob
## 1 (FERTILIZER) > 0 0.81 0.06 0.71 0.9 Inf 1
## Star
## 1 *
## ---
## 'CI': 90%-CI for one-sided and 95%-CI for two-sided hypotheses.
## '*': For one-sided hypotheses, the posterior probability exceeds 95%;
## for two-sided hypotheses, the value tested against lies outside the 95%-CI.
## Posterior probabilities of point hypotheses assume equal prior probabilities.
fert.brm3 %>%
hypothesis("FERTILIZER > 0") %>%
plot(ignore_prior = TRUE)
fert.brm3 %>%
hypothesis("FERTILIZER > 0") %>%
`[[`("samples") %>%
median_hdci()
Conclusions:
Alternatively…
fert.brm3 %>%
gather_draws(b_FERTILIZER) %>%
summarise(P = sum(.value > 0) / n())
## # A tibble: 1 × 2
## .variable P
## <chr> <dbl>
## 1 b_FERTILIZER 1
# OR
fert.brm3 %>%
tidy_draws() %>%
summarise(P = sum(b_FERTILIZER > 0) / n())
## # A tibble: 1 × 1
## P
## <dbl>
## 1 1
Conclusions:
fert.brm3 %>% hypothesis("FERTILIZER>0.9")
## Hypothesis Tests for class b:
## Hypothesis Estimate Est.Error CI.Lower CI.Upper Evid.Ratio
## 1 (FERTILIZER)-(0.9) > 0 -0.09 0.06 -0.19 0 0.06
## Post.Prob Star
## 1 0.05
## ---
## 'CI': 90%-CI for one-sided and 95%-CI for two-sided hypotheses.
## '*': For one-sided hypotheses, the posterior probability exceeds 95%;
## for two-sided hypotheses, the value tested against lies outside the 95%-CI.
## Posterior probabilities of point hypotheses assume equal prior probabilities.
fert.brm3 %>%
hypothesis("FERTILIZER>0.9") %>%
plot(ignore_prior = TRUE)
# This returns a list
fert.brm3 %>%
hypothesis("FERTILIZER>0.9") %>%
plot(ignore_prior = TRUE) %>%
`[[`(1) +
geom_vline(xintercept = 0, linetype = "dashed")
# OR
fert.brm3 %>%
tidy_draws() %>%
summarise(P = sum(b_FERTILIZER > 0.9) / n())
## # A tibble: 1 × 1
## P
## <dbl>
## 1 0.0542
fert.brm3 %>%
tidy_draws() %>%
ggplot(aes(x = b_FERTILIZER)) +
geom_density(fill = "orange") +
geom_vline(xintercept = 0.9, linetype = "dashed")
newdata <- list(FERTILIZER = c(200, 100))
fert.brm3 %>%
emmeans(~FERTILIZER, at = newdata) %>%
pairs()
## contrast estimate lower.HPD upper.HPD
## 200 - 100 80.6 69.7 92.6
##
## Point estimate displayed: median
## HPD interval probability: 0.95
Conclusions:
If we want to derive other properties, such as the percentage change, then we use tidy_draws() and then simple tidyverse spreadsheet operation.
It is in combination with emmeans() that tidy_draws() really comes into its own.
fert.mcmc <- fert.brm3 %>%
emmeans(~FERTILIZER, at = newdata) %>%
tidy_draws() %>%
rename_with(~ str_replace(., "FERTILIZER ", "p")) %>%
mutate(
Eff = p200 - p100,
PEff = 100 * Eff / p100
)
fert.mcmc %>% head()
Now we can calculate the medians and HPD intervals of each column (and ignore the .chain, .iteration and .draw).
fert.mcmc %>%
tidyMCMC(
estimate.method = "median",
conf.int = TRUE, conf.method = "HPDinterval"
)
Alternatively, we could use median_hdci() to focus on a specific column.
fert.mcmc %>% median_hdci(PEff)
fert.mcmc %>%
ggplot() +
geom_density(aes(x = PEff))
Conclusions:
To get the probability that the effect is greater than a 50% increase.
fert.mcmc %>% summarise(P = sum(PEff > 50) / n())
## # A tibble: 1 × 1
## P
## <dbl>
## 1 0.974
Conclusions:
Finally, we could alternatively use hypothesis(). Note that when we do so, the estimate is the difference between the effect and the hypothesised effect (50%).
fert.mcmc %>% hypothesis("PEff>50")
## Hypothesis Tests for class :
## Hypothesis Estimate Est.Error CI.Lower CI.Upper Evid.Ratio Post.Prob
## 1 (PEff)-(50) > 0 10.64 5.66 1.59 20.12 37.1 0.97
## Star
## 1 *
## ---
## 'CI': 90%-CI for one-sided and 95%-CI for two-sided hypotheses.
## '*': For one-sided hypotheses, the posterior probability exceeds 95%;
## for two-sided hypotheses, the value tested against lies outside the 95%-CI.
## Posterior probabilities of point hypotheses assume equal prior probabilities.
fert.list <- with(fert, list(FERTILIZER = seq(min(FERTILIZER), max(FERTILIZER), len = 100)))
newdata <- emmeans(fert.rstanarm3, ~FERTILIZER, at = fert.list) %>% as.data.frame()
head(newdata)
ggplot(newdata, aes(y = emmean, x = FERTILIZER)) +
geom_point(data = fert, aes(y = YIELD)) +
geom_line() +
geom_ribbon(aes(ymin = lower.HPD, ymax = upper.HPD), fill = "blue", alpha = 0.3) +
scale_y_continuous("YIELD") +
scale_x_continuous("FERTILIZER") +
theme_classic()
## spaghetti plot
newdata <- emmeans(fert.rstanarm3, ~FERTILIZER, at = fert.list) %>%
gather_emmeans_draws()
newdata %>% head()
ggplot(newdata, aes(y = .value, x = FERTILIZER)) +
geom_line(aes(group = .draw), alpha = 0.01) +
geom_point(data = fert, aes(y = YIELD))
fert.grid <- with(fert, list(FERTILIZER = modelr::seq_range(FERTILIZER, n = 100)))
newdata <- fert.brm3 %>%
emmeans(~FERTILIZER, at = fert.grid) %>%
as.data.frame()
head(newdata)
ggplot(newdata, aes(y = emmean, x = FERTILIZER)) +
geom_point(data = fert, aes(y = YIELD)) +
geom_line() +
geom_ribbon(aes(ymin = lower.HPD, ymax = upper.HPD), fill = "blue", alpha = 0.3) +
scale_y_continuous("YIELD") +
scale_x_continuous("FERTILIZER") +
theme_classic()
## spaghetti plot
newdata <- emmeans(fert.brm3, ~FERTILIZER, at = fert.grid) %>%
gather_emmeans_draws()
newdata %>% head()
ggplot(newdata, aes(y = .value, x = FERTILIZER)) +
geom_line(aes(group = .draw), color = "blue", alpha = 0.01) +
geom_point(data = fert, aes(y = YIELD))